from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet,ModelViewSet

from apps.meiduo_admin.serializers.orders import OrdersSimpleSer, OrderSer
from apps.meiduo_admin.utils.MeiduoPage import PageNum
from apps.orders.models import OrderInfo


class OrdersSimpleViewSet(ReadOnlyModelViewSet):


    def get_queryset(self):
        keyword=self.request.data.get('keyword')
        if keyword:
            return OrderInfo.objects.filter(order_id__contains=keyword)
        else:
            return OrderInfo.objects.order_by('-create_time')

    def get_serializer_class(self):

        if self.action=='retrieve':
            return OrderSer
        elif self.action=='list':
            return OrdersSimpleSer
    #
    # @action(methods=['PUT'],detail=True)
    # def status(self,request,*args,**kwargs):
    #     instance=self.get_object()
    #     instance.status=3
    #     instance.save()
    #
    #     return Response({
    #         'order_id':instance.order_id,
    #         "status": instance.status
    #     },status=201)
    @action(methods=['PUT'], detail=True)
    def status(self, request, *args, **kwargs):
        # detail=True===>put /orders/(?P<pk>[^/.]+)/status/
        # detail=False==>put /orders/status/
        # 修改指定订单的状态

        instance = self.get_object()


        instance.status = 3
        instance.save()

        return Response({
            'order_id': instance.order_id,
            'status': instance.status
        }, status=201)


    pagination_class = PageNum
    # serializer_class = OrdersSimpleSer